﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Ninesky.Entities;

namespace Ninesky.WebAPI.Controllers
{
    [Produces("application/json")]
    [Route("api/User")]
    [EnableCors("AllowDomain")]
    public class UserController : Controller
    {
        [AllowAnonymous]
        [HttpGet("Token")]
        public IActionResult GetToken()
        {
            var jwtConfig = ((IOptionsMonitor<JwtConfig>)HttpContext.RequestServices.GetService(typeof(IOptionsMonitor<JwtConfig>))).CurrentValue;
            //Token是否合法
            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim("utyp", UserType.Anonymous.ToString()));
            JwtSecurityTokenHandler jwtTokenHandler = new JwtSecurityTokenHandler();
            SecurityToken anonymousToken = new JwtSecurityToken(issuer: jwtConfig.Issuer,
                signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.Secret)), jwtConfig.Algorithm),
                expires: DateTime.Now.AddDays(1),
                claims: claims
                );
            return Ok(jwtTokenHandler.WriteToken(anonymousToken));
        }
        [AllowAnonymous]
        [HttpGet]
        public IActionResult Get()
        {
            return Ok("ddd");
        }
    }
}